package com.fingard.dsp.bank.directbank.hebbank01;

import com.fingard.FGBiz;
import com.fingard.constant.Format;
import com.fingard.dsp.bank.directConfig.FtpSet;
import com.fingard.dsp.bank.directbank.bankInterface.IReceipt;
import com.fingard.dsp.bank.helpers.DataFileHelper;
import com.fingard.dsp.bank.reqrespobj.downloadreceipt.ReqQryReceipt;
import com.fingard.dsp.bank.reqrespobj.downloadreceipt.RetAtsReceipt;
import com.fingard.io.FileHelper;
import com.fingard.net.FtpReceiver;
import com.fingard.net.SftpPortClient;
import com.fingard.text.StringHelper;
import com.fingard.util.DateHelper;
import com.fingard.util.SmbFileUtil;
import com.fingard.util.ZipHelper;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

import java.io.File;
import java.util.*;

/**
 * @author Parker on 2019-10-16.
 * @version 1.0
 */
public class HEBBANK01Receipt extends HEBBANK01Base implements IReceipt {
    @Override
    public RetAtsReceipt qryReceipt(ReqQryReceipt p_reqReceipt) throws Exception {
        RetAtsReceipt retAts = new RetAtsReceipt(p_reqReceipt.reqHeader);
        retAts.writeStart();
        String receiptSaveToMainDir = FGBiz.dspCenter.dspSet.receiptMainDir;
        if (!StringHelper.isNullOrEmpty(receiptSaveToMainDir)) {
            if (!StringHelper.isNullOrEmpty(FGBiz.dspCenter.dspSet.receiptShareDir)) {
                if (!StringHelper.isNullOrEmpty(FGBiz.dspCenter.dspSet.receiptPushServerUrl)) {
                    download(p_reqReceipt, retAts);
                } else {
                    retAts.respInfo = "DSPSystem未配置回单文件推送地址";
                    retAts.respCode = "-1";
                }
            } else {
                retAts.respCode = "-1";
                retAts.respInfo = "DSPSystem未配置回单文件共享目录";
            }
        } else {
            retAts.respCode = "-1";
            retAts.respInfo = "DSPSystem未配置回单文件下载保存主目录";
        }
        retAts.writeRetToATS();
        return retAts;
    }

    private void download(ReqQryReceipt p_reqReceipt, RetAtsReceipt retAts) {
        try {
            Calendar tmpCalendarFrom = Calendar.getInstance();
            tmpCalendarFrom.setTime(p_reqReceipt.getDateFrom());
            Calendar tmpCalendarTo = Calendar.getInstance();
            tmpCalendarTo.setTime(p_reqReceipt.getDateTo());
            int tmpIntFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));
            int tmpIntTo = Integer.parseInt(Format.Date8Format.format(tmpCalendarTo.getTime()));
            StringBuilder json = new StringBuilder();
            json.append("transType=downloadreceipt&data={\"rows\":[");
            DataFileHelper dFileHelper = new DataFileHelper(this);
            StringBuilder tempMSG = new StringBuilder();
            int tmpFileCount = 0;
            while (tmpIntFrom <= tmpIntTo) {
                HEBBANK01Header bankHeader = new HEBBANK01Header();
                bankHeader.bsnCode = "CBE018";
                bankHeader.serialNo = p_reqReceipt.reqHeader.transSeqID;
                XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
                writeCommonHeader(xmlWriter, bankHeader);
                xmlWriter.writeStartElement("ReqParam");
                xmlWriter.writeElementString("Account_num", p_reqReceipt.actNum);//账号
                xmlWriter.writeElementString("receiptDate", tmpIntFrom + "");//查询日期
                xmlWriter.writeEndElement();
                xmlWriter.writeEndDocument();

                List<Map<String, String>> dataList = new ArrayList<Map<String, String>>();

                String[] bankResult = sendToBank(xmlWriter.toXmlString(), bankHeader);
                if (bankResult[0].length() == 0) {
                    String[] result = bankResult[1].split("\\|");
                    if ("0000".equals(result[0])) {
                        StringBuilder tmpSbMsg = new StringBuilder();
                        String xmlStr = bankResult[1].substring(bankResult[1].indexOf("|#") + 2);
                        XmlTextReader tmpBkReader = loadBankRespXmlReader(xmlStr, tmpSbMsg);
                        if (tmpBkReader != null) {
                            String returnCode = tmpBkReader.getFirstText("/SCCBEBankData/opRep/opResult/stt");
                            String returnMsg = tmpBkReader.getFirstText("/SCCBEBankData/opRep/opResult/pointInfor");
                            if ("1".equals(returnCode) || "0".equals(returnCode)) {
                                //查询回单明细
                                xmlWriter = new XmlTextWriter();//发银行报文的XML对象
                                bankHeader.bsnCode = "CBE027";
                                bankHeader.serialNo = p_reqReceipt.reqHeader.transSeqID;
                                writeCommonHeader(xmlWriter, bankHeader);
                                xmlWriter.writeStartElement("ReqParam");
                                xmlWriter.writeElementString("saCardNo", p_reqReceipt.actNum);//卡号
                                xmlWriter.writeElementString("saAcctNo", p_reqReceipt.actNum);//账号
                                xmlWriter.writeElementString("saTxDt1", tmpIntFrom + "");//交易日期区间(开始)
                                xmlWriter.writeElementString("saTxDt2", tmpIntFrom + "");//交易日期区间(结束)
                                xmlWriter.writeEndElement();
                                xmlWriter.writeEndDocument();

                                bankResult = sendToBank(xmlWriter.toXmlString(), bankHeader);
                                if (bankResult[0].length() == 0) {
                                    result = bankResult[1].split("\\|");
                                    if ("0000".equals(result[0])) {
                                        tmpSbMsg = new StringBuilder();
                                        xmlStr = bankResult[1].substring(bankResult[1].indexOf("|#") + 2);
                                        tmpBkReader = loadBankRespXmlReader(xmlStr, tmpSbMsg);
                                        if (tmpBkReader != null) {
                                            String dateCount = tmpBkReader.getFirstText("/SCCBEBankData/opRep/opResult/pageCount");
                                            if (Integer.parseInt(dateCount) > 0) {
                                                while (tmpBkReader.read("/SCCBEBankData/opRep/opResult/qryBillInfo/row")) {
                                                    Map<String, String> dataMap = new HashMap<String, String>();
                                                    //返回报文与我们需要数据之间的对应
                                                    dataMap.put("saTxLogNo", tmpBkReader.readedXElement.getSingleText("saTxLogNo"));//交易流水
                                                    dataMap.put("saTxAmt", tmpBkReader.readedXElement.getSingleText("saTxAmt"));//交易金额
                                                    dataMap.put("dCardNo", tmpBkReader.readedXElement.getSingleText("dCardNo"));//对方账号
                                                    dataMap.put("dAcctName", tmpBkReader.readedXElement.getSingleText("dAcctName"));//对方户名
                                                    dataMap.put("dcFlag", tmpBkReader.readedXElement.getSingleText("dcFlag"));//借贷标志
                                                    dataMap.put("acctTxSeq", tmpBkReader.readedXElement.getSingleText("acctTxSeq"));//交易序号
                                                    dataList.add(dataMap);
                                                }
                                            } else {
                                                WriteBankLogLn("查询" + tmpIntFrom + "日回单文件失败,原因:返回回单数据为空");
                                                retAts.writeRespCode("-1");
                                                retAts.writeRespInfo("查询" + tmpIntFrom + "日回单文件失败,原因:返回回单数据为空");
                                                break;
                                            }
                                        } else {
                                            retAts.writeRespCode("-1");
                                            retAts.writeRespInfo(tmpSbMsg.toString());
                                            WriteBankLogLn("查询" + tmpIntFrom + "日回单文件失败,原因:" + tmpSbMsg.toString());
                                            break;
                                        }
                                    } else {
                                        WriteBankLogLn("查询" + tmpIntFrom + "日回单文件失败,原因:" + result[1]);
                                        retAts.writeRespCode("-1");
                                        retAts.writeRespInfo(result[1]);
                                        break;
                                    }
                                } else {
                                    WriteBankLogLn("查询" + tmpIntFrom + "日回单文件失败,原因:" + bankResult[1]);
                                    retAts.writeRespCode("-1");
                                    retAts.writeRespInfo(bankResult[1]);
                                    break;
                                }
                            } else {
                                WriteBankLogLn("查询" + tmpIntFrom + "日回单文件失败,原因:" + returnMsg);
                                retAts.writeRespCode("-1");
                                retAts.writeRespInfo(returnMsg);
                                break;
                            }
                        } else {
                            retAts.writeRespCode("-1");
                            retAts.writeRespInfo(tmpSbMsg.toString());
                            WriteBankLogLn("查询" + tmpIntFrom + "日回单文件失败,原因:" + tmpSbMsg.toString());
                            break;
                        }
                    } else {
                        WriteBankLogLn("查询" + tmpIntFrom + "日回单文件失败,原因:" + result[1]);
                        retAts.writeRespCode("-1");
                        retAts.writeRespInfo(result[1]);
                        break;
                    }
                } else {
                    WriteBankLogLn("查询" + tmpIntFrom + "日回单文件失败,原因:" + bankResult[1]);
                    retAts.writeRespCode("-1");
                    retAts.writeRespInfo(bankResult[1]);
                    break;
                }

                FtpSet ftpSet = bankFront.getFtpSet("receipt");
                ftpSet.downDir = StringHelper.trimEndFileSp(ftpSet.downDir) + "/";
                ftpSet.upDir = StringHelper.trimEndFileSp(ftpSet.upDir) + "/";
                SftpPortClient sftpPortClient = null;
                try {
                    sftpPortClient = new SftpPortClient(ftpSet);
                    String fileName = tmpIntFrom + "_" + p_reqReceipt.actNum + ".zip";
                    String localDir = FGBiz.dspCenter.dspSet.receiptMainDir + File.separator + reqHeader.bankCode + File.separator + String.valueOf(tmpIntFrom).substring(0, 6) +
                            File.separator + String.valueOf(tmpIntFrom).substring(6, 8) + File.separator + p_reqReceipt.actNum;

                    if (!FileHelper.existFile(localDir)) {
                        FileHelper.mkdir(localDir);
                    }
                    WriteBankLogLn("***********连接SFTP服务器开始***********");
                    FtpReceiver receiver = sftpPortClient.downloadFile("", fileName, localDir);

                    sftpPortClient.disconnect();
                    WriteBankLogLn("***********连接SFTP服务器结束***********");
                    if (receiver.isCompleted) {
                        WriteBankLogLn("文件下载已完成，开始解压...解压至：[" + localDir + "]");
                        ZipHelper.unzipFile(localDir + File.separator + fileName, localDir);
                        WriteBankLogLn("文件解压已完成.");
                        File depressDir = new File(localDir + File.separator + fileName.replace(".zip", ""));
                        String destPath = depressDir.getAbsolutePath();
                        String[] parentFile = FileHelper.listFiles(destPath);
                        for (String pfile : parentFile) {
                            String[] files = FileHelper.listFiles(destPath + File.separator + pfile);
                            if (files == null) {
                                WriteBankLogLn("解压后文件夹" + destPath + "下为空");
                                continue;
                            }
                            for (String file : files) {
                                String localRecipt = destPath + File.separator + pfile + File.separator + file;
                                if ((file.endsWith(".PDF") || file.endsWith(".pdf"))) {
                                    int result = -1;
                                    String tmpByDate = Format.Date8Format.format(new Date());
                                    tmpByDate = tmpByDate.substring(0, 6) + "/" + tmpByDate.substring(6, 8) + "/"
                                            + this.reqHeader.bankCode + "/" + p_reqReceipt.actNum + "/";
                                    if ("localhost".equals(SmbFileUtil.getUploadType())) {//上传到本地目录
                                        String shareDir = StringHelper.trimEndFileSp(FGBiz.dspCenter.dspSet.receiptShareDir.split("@")[1]) + File.separator;
                                        WriteBankLogLn("正在上传文件至本地共享目录:" + shareDir);
                                        result = FileHelper.copyFile(localRecipt, shareDir + tmpByDate + file);
                                    } else {//上传到共享文件夹
                                        if (new File(localRecipt).exists()) {
                                            WriteBankLogLn(
                                                    "正在上传文件至共享目录:" + FGBiz.dspCenter.dspSet.receiptShareDir);
                                            result = SmbFileUtil.smbUploading(localRecipt, tmpByDate,
                                                    FGBiz.dspCenter.dspSet.receiptShareDir);
                                        }
                                    }
                                    if (result == 0 || result == 1) {
                                        if (result == 0) {
                                            WriteBankLogLn("文件上传成功");
                                            tmpFileCount++;
                                        } else {
                                            WriteBankLogLn("文件已存在共享目录无需重复上传");
                                        }

                                        //String content = PdfGenerateUtil.readFileOfPDF(localRecipt);
                                        //String receiptCode = content.substring(content.indexOf("回单号：") + 4, content.indexOf("回单号：") + 24);
                                        Iterator<Map<String, String>> mapIterator = dataList.iterator();
                                        while (mapIterator.hasNext()) {
                                            Map<String, String> tmpMap = mapIterator.next();
                                            if (file.replace(".PDF", "").replace(".pdf", "").endsWith(tmpMap.get("acctTxSeq"))) {
                                                // 推送数据给ATS处理
                                                json.append("{");
                                                json.append("\"actNum\":\"" + p_reqReceipt.actNum + "\",");
                                                json.append("\"actCur\":\"" + p_reqReceipt.actCur + "\",");
                                                json.append("\"receiptCode\":\"" + tmpMap.get("saTxLogNo") + "\",");
                                                json.append("\"receiptType\":\"" + "" + "\",");
                                                json.append("\"receiptState\":\"" + "" + "\",");
                                                json.append("\"oppActName\":\"" + tmpMap.get("dAcctName") + "\",");
                                                json.append("\"oppActNum\":\"" + tmpMap.get("dCardNo") + "\",");
                                                if ("C".equalsIgnoreCase(tmpMap.get("dcFlag"))) {
                                                    json.append("\"moneyway\":\"" + "2" + "\",");
                                                } else {
                                                    json.append("\"moneyway\":\"" + "1" + "\",");
                                                }
                                                json.append("\"amount\":\"" + "" + tmpMap.get("saTxAmt") + "\",");
                                                json.append("\"tranSeqNo\":\"" + tmpMap.get("saTxLogNo") + "\",");
                                                json.append("\"tranCode\":\"" + "" + "\",");
                                                json.append("\"tranDate\":\"" + DateHelper.convertD8toD10(tmpIntFrom + "") + "\",");
                                                json.append("\"filePath\":\"" + tmpByDate
                                                        + StringHelper.getFileName(localRecipt) + "\",");
                                                json.append("\"fileType\":\"1\"");
                                                json.append("},");
                                                mapIterator.remove();
                                                break;
                                            }
                                        }
                                    } else {
                                        WriteBankLogLn(tmpIntFrom + ":上传文件至共享目录失败，请检查共享目录配置是否正确 ");
                                        break;
                                    }
                                }
                            }
                        }
                    } else {
                        WriteBankLogLn("连接SFTP失败，请检查配置、通道是否正常,文件是否存在。失败原因：\r\n" + receiver.connMsg);
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                    WriteBankLogLn("上传文件失败：" + e);
                }
                tmpCalendarFrom.add(Calendar.DAY_OF_MONTH, 1);
                tmpIntFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));
            }
            WriteBankLogLn("成功保存了" + tmpFileCount + "个文件");
            retAts.respCode = "0";
            retAts.respInfo = "成功保存了" + tmpFileCount + "个文件" + tempMSG;
            WriteBankLogLn("成功保存了" + tmpFileCount + "个文件" + tempMSG);
            json.append("]}");
            if (tmpFileCount > 0) {
                String[] data = sendToATS(json.toString());
                if (data[0].length() == 0 && "ok".equals(data[1])) {
                    retAts.respCode = "0";
                    retAts.respInfo = "推送数据到ATS成功,请查看数据";
                    WriteBankLogLn("推送数据到ATS成功,请查看数据");
                } else {
                    retAts.respCode = "0";
                    retAts.respInfo = "推送数据到ATS失败";
                    WriteBankLogLn("推送数据到ATS失败");
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            retAts.respCode = "-1";
            retAts.respInfo = ex.getMessage();
            WriteBankLogLn(ex);
        }
    }
}
